﻿using BO.Infrastructure.Config;
using BO.Infrastructure.Utils;
using BO.ProjectManager;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Xml;

namespace GUI.ProjectManager.CssAndJs
{
    public partial class Generate : System.Web.UI.Page
    {
        protected void btnGenerate_Click(object sender, EventArgs e)
        {
            var filepath = HttpContext.Current.Server.MapPath("/App_Data/combres.xml");
            var configPath = HttpContext.Current.Server.MapPath("/App_Data/cssAndJsConfig.xml");
            if (File.Exists(filepath) && File.Exists(configPath))
            {
                var doc = new XmlDocument();


                doc.Load(filepath);
                var sets = doc.GetElementsByTagName("resourceSet");
                var currentStorageSetting = PMBO.GetCurrentStorageConfig();
                if (sets.Count > 0 && currentStorageSetting != null)
                {

                    foreach (XmlElement set in sets)
                    {
                        var name = set.GetAttribute("name");
                        var type = set.GetAttribute("type");

                        if (!string.IsNullOrEmpty(name))
                        {
                            var url = string.Format("{0}{1}", AppSettings.Domain.TrimEnd('/'), Combres.WebExtensions.CombresUrl(name));
                            var request = WebRequest.Create(url);
                            var response = (HttpWebResponse)request.GetResponse();

                            var stream = response.GetResponseStream();

                            if (stream != null)
                            {
                                var reader = new StreamReader(stream, Encoding.UTF8);
                                var responseText = reader.ReadToEnd();
                                reader.Close();
                                response.Close();

                                if (!string.IsNullOrEmpty(responseText))
                                {
                                    var compresSourcepath = string.Format("/CombresStaticContent/{0}_{2}.{1}", name, type, currentStorageSetting.DefaultVersion);
                                    File.WriteAllText(Server.MapPath(compresSourcepath), responseText);
                                }
                            }
                        }
                    }
                }
            }
        }


    }
}